<template>
  <div class="user-management">
    <h1>用户管理</h1>
    
    <!-- 搜索和操作区 -->
    <el-card class="search-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入用户名或邮箱搜索"
            prefix-icon="el-icon-search"
            clearable
          ></el-input>
        </el-col>
        <el-col :span="8">
          <el-select v-model="searchForm.role" placeholder="选择角色" clearable>
            <el-option label="全部" value=""></el-option>
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="编辑" value="editor"></el-option>
          </el-select>
        </el-col>
        <el-col :span="8" class="text-right">
          <el-button type="primary" @click="handleCreateUser">
            <i class="el-icon-plus"></i> 新增用户
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 用户列表 -->
    <el-card class="data-card">
      <el-table :data="filteredUsers" style="width: 100%">
        <el-table-column type="index" label="序号" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="role" label="角色" width="120">
          <template #default="scope">
            <el-tag :type="getRoleType(scope.row.role)">
              {{ getRoleLabel(scope.row.role) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="active"
              inactive-value="inactive"
              @change="handleStatusChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEditUser(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDeleteUser(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredUsers.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 用户编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEditMode ? '编辑用户' : '新增用户'"
      width="500px"
    >
      <el-form :model="editForm" :rules="rules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="editForm.role" placeholder="请选择角色">
            <el-option label="管理员" value="admin"></el-option>
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="编辑" value="editor"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="editForm.status" placeholder="请选择状态">
            <el-option label="活跃" value="active"></el-option>
            <el-option label="禁用" value="inactive"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="!isEditMode" label="密码" prop="password">
          <el-input v-model="editForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSaveUser">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { api } from '../utils/axios'
const { get, post, put, delete: del } = api
import { ElMessage, ElMessageBox } from 'element-plus'
import { users } from '../utils/mockData.js'

// 用户数据
const userList = ref([])

// 搜索表单
const searchForm = reactive({
  keyword: '',
  role: ''
})

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10
})

// 对话框配置
const dialogVisible = ref(false)
const isEditMode = ref(false)
const editFormRef = ref()
const editForm = reactive({
  id: '',
  username: '',
  email: '',
  role: '',
  status: 'active',
  password: ''
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
  ]
}

// 过滤后的用户数据
const filteredUsers = computed(() => {
  let result = [...userList.value]
  
  // 按关键词过滤
  if (searchForm.keyword) {
    const keyword = searchForm.keyword.toLowerCase()
    result = result.filter(user => 
      user.username.toLowerCase().includes(keyword) || 
      user.email.toLowerCase().includes(keyword)
    )
  }
  
  // 按角色过滤
  if (searchForm.role) {
    result = result.filter(user => user.role === searchForm.role)
  }
  
  return result
})

// 获取角色对应的标签类型
const getRoleType = (role) => {
  const roleMap = {
    admin: 'danger',
    editor: 'warning',
    user: 'success'
  }
  return roleMap[role] || 'info'
}

// 获取角色对应的标签文本
const getRoleLabel = (role) => {
  const roleMap = {
    admin: '管理员',
    editor: '编辑',
    user: '普通用户'
  }
  return roleMap[role] || role
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 加载用户数据
const loadUsers = () => {
  userList.value = JSON.parse(JSON.stringify(users))
}

// 创建用户
const handleCreateUser = () => {
  isEditMode.value = false
  Object.assign(editForm, {
    id: '',
    username: '',
    email: '',
    role: '',
    status: 'active',
    password: ''
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEditUser = (user) => {
  isEditMode.value = true
  Object.assign(editForm, {
    id: user.id,
    username: user.username,
    email: user.email,
    role: user.role,
    status: user.status
  })
  dialogVisible.value = true
}

// 保存用户
const handleSaveUser = async () => {
  await editFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (isEditMode.value) {
        // 编辑用户
        const index = userList.value.findIndex(u => u.id === editForm.id)
        if (index !== -1) {
          userList.value[index] = {
            ...userList.value[index],
            username: editForm.username,
            email: editForm.email,
            role: editForm.role,
            status: editForm.status
          }
          ElMessage.success('用户编辑成功')
        }
      } else {
        // 创建新用户
        const newUser = {
          id: Date.now(),
          username: editForm.username,
          email: editForm.email,
          password: editForm.password,
          role: editForm.role,
          status: editForm.status,
          createTime: new Date().toISOString(),
          token: `mock-token-${Date.now()}`
        }
        userList.value.unshift(newUser)
        ElMessage.success('用户创建成功')
      }
      dialogVisible.value = false
    } catch (error) {
      ElMessage.error('操作失败，请重试')
    }
  })
}

// 删除用户
const handleDeleteUser = (userId) => {
  ElMessageBox.confirm(
    '确定要删除这个用户吗？',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const index = userList.value.findIndex(u => u.id === userId)
    if (index !== -1) {
      userList.value.splice(index, 1)
      ElMessage.success('用户删除成功')
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 切换用户状态
const handleStatusChange = (user) => {
  ElMessage.success(`${user.username} 状态已更新`)
}

// 分页处理
const handleSizeChange = (size) => {
  pagination.pageSize = size
}

const handleCurrentChange = (current) => {
  pagination.currentPage = current
}

// 组件挂载时加载数据
onMounted(() => {
  loadUsers()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
  height: 100%;
}

.search-card {
  margin-bottom: 20px;
}

.data-card {
  height: calc(100% - 120px);
  display: flex;
  flex-direction: column;
}

.el-table {
  flex: 1;
  overflow: auto;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>